package com.enlorenz.core.channel.socket.common.util;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SocketChannel;

/**
 * 新IO工具
 * @author MAC
 */
public class NioUtil {
	
	/**
	 * 读取制定长度的数据
	 * @param channel
	 * @param commBuffer
	 * @param limitLen
	 * @return
	 * @throws IOException
	 */
	public static byte [] read(SocketChannel channel, ByteBuffer commBuffer,int limitLen) throws IOException{
		//清理缓存
		commBuffer.clear();
		//限制读取长度
		commBuffer.limit(limitLen);
		//读取消息
		int onceRead = channel.read(commBuffer);
		byte[] bytes =null;
		if (onceRead > 0) {
			// 从通讯缓冲中拷贝出读到的数据
			bytes= new byte[onceRead];
			commBuffer.flip();
			commBuffer.get(bytes);
		}else if (onceRead == -1) {
			throw new ClosedChannelException();
		}
		return bytes;
	}
	
}
